package com.yu.mall.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yu.mall.dto.AfsApplyInfoItem;
import com.yu.mall.dto.LogisticsDto;
import com.yu.mall.dto.LogisticsReqDto;
import com.yu.mall.dto.PageDTO;
import com.yu.mall.dto.PostSalesDto;
import com.yu.mall.dto.PostSalesReqDto;
import com.yu.mall.dto.WaybillInfo;
import com.yu.mall.entity.Address;
import com.yu.mall.entity.OrderItem;
import com.yu.mall.entity.PostSales;
import com.yu.mall.entity.PostSalesExample;
import com.yu.mall.mapper.AddressMapper;
import com.yu.mall.mapper.OrderItemMapper;
import com.yu.mall.mapper.OrderMapper;
import com.yu.mall.mapper.PostSalesMapper;
import com.yu.mall.service.OrderService;
import com.yu.mall.service.PostSalesService;
import com.yu.mall.util.JDUtils;
import com.yu.mall.util.ListSortUtil;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.ResultVO;
import com.yu.mall.vo.order.OrderItemVO;
import com.yu.mall.vo.order.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("orderPostSales")
@Api(tags = "售后管理", value = "售后管理")
@Slf4j
public class OrderPostSalesController {

    @Resource
    private PostSalesService postSalesService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AddressMapper addressMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private PostSalesMapper postSalesMapper;
    @Resource
    private OrderService orderService;

    private static Map<Integer,String> customerExpectMap = new HashMap<>();
    private static Map<Integer,String> pickupWareTypeMap = new HashMap<>();
    private static Map<Integer,String> customerExpectItemMap = new HashMap<>();
    private static Map<Integer,String> pickupWareTypeItemMap = new HashMap<>();
    static{
        customerExpectMap.put(10,"退货");
        customerExpectMap.put(20,"换货");
        pickupWareTypeMap.put(4,"上门取件");
        pickupWareTypeMap.put(7,"送至自提点");
        pickupWareTypeMap.put(40,"自行邮寄");
        customerExpectItemMap.put(10, "{'name':'退货','key':10}");
        customerExpectItemMap.put(20, "{'name':'换货','key':20}");
        pickupWareTypeItemMap.put(4, "{'name':'上门取件','key':4}");
        pickupWareTypeItemMap.put(7, "{'name':'送至自提点','key':7}");
        pickupWareTypeItemMap.put(40, "{'name':'自行邮寄','key':40}");
    }

    @PostMapping("getSupport")
    @ApiOperation(value = "查询订单售后支持情况列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value="商品名称或者订单编号"),
            @ApiImplicitParam(name = "skuId",value="skuId"),
            @ApiImplicitParam(name = "status",value="订单状态（1 待付款，2 待收货，3 已完成 4 已取消）")
    })
    public ResultVO<List<OrderVO>> getSupport(PageDTO dto, String name, String skuId,String status) {
        try {
            ResultVO<List<OrderVO>> orderResult = orderService.list(dto, name, status);
            List<OrderVO> orderList = orderResult.getData();
            if(CollectionUtils.isNotEmpty(orderList)){
                for (OrderVO orderVO : orderList) {
                    if(Arrays.asList("2","3").contains(orderVO.getStatus())){
                        if(StrUtil.isNotBlank(skuId)){
                            Map<String, OrderItemVO> skuIdMap = ListSortUtil.listToMap(orderVO.getOrderItems(), "skuId");
                            orderVO.setOrderItems(Arrays.asList(skuIdMap.get(skuId)));
                        }
                        setShInfo(orderVO);
                    }
                }
            }
            return ResultUtils.success(orderList);
        } catch (Exception e) {
            log.error("查询订单售后支持情况列表，出错", e);
        }
        return ResultUtils.error("查询失败");
    }

    private void setShInfo(OrderVO orderVO){
        try {
            List<OrderItemVO> orderItems = orderVO.getOrderItems();
            for (OrderItemVO orderItem : orderItems) {
                Map<String, Object> map = JDUtils.afterSaleNewGetGoodsAttributes(orderItem.getJdOrderId(), Arrays.asList(orderItem.getSkuId()));
                JSONArray data = (JSONArray)map.get("data");
                JSONObject jsonObj = data.getJSONObject(0);
                List<Integer> customerExpect = (List<Integer>)jsonObj.get("customerExpect");
                List<Integer> pickupWareType = (List<Integer>)jsonObj.get("pickupWareType");
                if(CollectionUtils.isNotEmpty(customerExpect) && CollectionUtils.isNotEmpty(pickupWareType)){
                    if(customerExpect.size() == 1 && customerExpect.get(0) == 30){
                        orderItem.setShFlag(false);
                    }else{
                        orderItem.setShFlag(true);
                        List<JSONObject> customerExpectList = new ArrayList<>();
                        for (Integer key : customerExpect) {
                            if(customerExpectItemMap.containsKey(key)){
                                customerExpectList.add(JSONObject.parseObject(customerExpectItemMap.get(key)));
                            }
                        }
                        orderItem.setCustomerExpect(customerExpectList);
                        List<JSONObject> pickupWareTypeList = new ArrayList<>();
                        for (Integer key : pickupWareType) {
                            if(pickupWareTypeItemMap.containsKey(key)){
                                pickupWareTypeList.add(JSONObject.parseObject(pickupWareTypeItemMap.get(key)));
                            }
                        }
                        orderItem.setPickupWareType(pickupWareTypeList);
                        orderItem.setWareNum(jsonObj.getInteger("wareNum"));
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询订单支持售后详情出错,orderVO:{}", JSON.toJSONString(orderVO), e);
        }
    }

    @PostMapping("listQuery")
    @ApiOperation(value = "查询申请售后记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态，1进行中，不传查所有"),
            @ApiImplicitParam(name = "orderNo", value = "系统订单编号"),
            @ApiImplicitParam(name = "thirdApplyId", value = "京东售后编号")})
    public ResultVO<List<PostSales>> listQuery(String status,String orderNo,String thirdApplyId, PageDTO dto) {
        Integer pageNum = dto.getPageNo();
        Integer pageSize = dto.getPageSize();
        if (null == pageNum || pageNum < 1) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize < 1 || pageSize > 100) {
            pageSize = 10;
        }
        try {
            List<PostSales> list = postSalesService.pageQueryList(dto.getOpenid(),status,orderNo,thirdApplyId, pageNum, pageSize);
            if(StrUtil.isNotBlank(thirdApplyId)){
                Address qjAddress = new Address();
                qjAddress.setId(Integer.parseInt(list.get(0).getQjAddressId()));
                qjAddress = addressMapper.selectOne(qjAddress);
                list.get(0).setQjAddressId(JSON.toJSONString(qjAddress));
            }
            return ResultUtils.success(list);
        } catch (Exception e) {
            log.error("查询售后列表，出错", e);
        }
        return ResultUtils.error("操作失败");
    }

    @PostMapping("pushApply")
    @ApiOperation(value = "申请售后")
    public ResultVO<JSONArray> pushApply(PostSalesReqDto reqDto) {
        try {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(reqDto.getOrderNo());
            orderItem.setSkuId(reqDto.getWareId());
            orderItem = orderItemMapper.selectOne(orderItem);
            PostSalesDto postSalesDto = new PostSalesDto();
            postSalesDto.setOrderId(orderItem.getJdOrderId());
            //取件地址
            Address qjAddress = new Address();
            qjAddress.setId(Integer.parseInt(reqDto.getQjAddressId()));
            qjAddress = addressMapper.selectOne(qjAddress);
            postSalesDto.setPickWareProvince(Integer.parseInt(qjAddress.getProvinceId()));
            postSalesDto.setPickWareCity(Integer.parseInt(qjAddress.getCityId()));
            postSalesDto.setPickWareCounty(Integer.parseInt(qjAddress.getCountyId()));
            postSalesDto.setPickWareVillage(Integer.parseInt(qjAddress.getTownId()));
            postSalesDto.setPickWareAddress(qjAddress.getAddress());
            //收件地址
            Address sjAddress = new Address();
            sjAddress.setId(Integer.parseInt(reqDto.getSjAddressId()));
            sjAddress = addressMapper.selectOne(sjAddress);
            postSalesDto.setReturnWareProvince(Integer.parseInt(sjAddress.getProvinceId()));
            postSalesDto.setReturnWareCity(Integer.parseInt(sjAddress.getCityId()));
            postSalesDto.setReturnWareCountry(Integer.parseInt(sjAddress.getCountyId()));
            postSalesDto.setReturnWareVillage(Integer.parseInt(sjAddress.getTownId()));
            postSalesDto.setReturnWareAddress(sjAddress.getAddress());
            //基础信息
            postSalesDto.setCustomerName(qjAddress.getName());
            postSalesDto.setCustomerContactName(qjAddress.getName());
            postSalesDto.setCustomerMobilePhone(qjAddress.getPhone());
            postSalesDto.setPickwareType(reqDto.getPickwareType());
            postSalesDto.setReturnWareType(10);
            //订单商品信息
            AfsApplyInfoItem item = new AfsApplyInfoItem();
            item.setCustomerExpect(reqDto.getCustomerExpect());
            item.setIsNeedDetectionReport(false);
            item.setLossPreventionTagFlag(false);
            item.setIsHasPackage(true);
            item.setPackageDesc(10);
            item.setQuestionDesc(reqDto.getQuestionDesc());
            item.setWareId(reqDto.getWareId());
            item.setMainWareId(reqDto.getWareId());
            item.setWareName(orderItem.getName());
            item.setWareNum(reqDto.getWareNum());
            item.setWareType(10);
            postSalesDto.setAfsApplyInfoItemList(Arrays.asList(item));
            postSalesDto.setThirdApplyId(System.currentTimeMillis()+"");
            String respStr = JDUtils.afterSaleNewCreateAfsApply(postSalesDto);
            log.info("订单申请售后结果，" + respStr);
            JSONObject respJson = JSONObject.parseObject(respStr);
            if ("true".equals(respJson.getString("success")) && "0000".equals(respJson.getString("resultCode"))) {
                PostSales postSales = new PostSales();
                postSales.setOpenid(reqDto.getOpenid());
                postSales.setOrderNo(reqDto.getOrderNo());
                postSales.setJdOrderId(orderItem.getJdOrderId());
                postSales.setThirdApplyId(postSalesDto.getThirdApplyId());
                postSales.setSkuId(reqDto.getWareId());
                postSales.setNum(reqDto.getWareNum());
                postSales.setJdPrice(orderItem.getPrice());
                postSales.setName(orderItem.getName());
                postSales.setImagePath(orderItem.getImagePath());
                postSales.setBrand(orderItem.getBrand());
                postSales.setSkuName(orderItem.getSkuName());
                postSales.setStatus("1");
                if(40 == postSalesDto.getPickwareType()){
                    postSales.setIsNeedOtherLogistics(true);
                }
                postSales.setCustomerExpect(customerExpectMap.get(reqDto.getCustomerExpect()));
                postSales.setPickupWareType(pickupWareTypeMap.get(reqDto.getPickwareType()));
                postSales.setQuestionDesc(reqDto.getQuestionDesc());
                postSales.setQjAddressId(reqDto.getQjAddressId());
                postSalesMapper.insertSelective(postSales);
                return ResultUtils.success("申请成功");
            }
        } catch (Exception e) {
            log.error("查询订单支持售后情况，出错", e);
        }
        return ResultUtils.error("申请失败");
    }

    @PostMapping("pushLogistics")
    @ApiOperation(value = "售后填写第三方订单信息")
    public ResultVO<JSONArray> pushLogistics(LogisticsReqDto reqDto) {
        try {
            PostSales postSales = postSalesMapper.selectByPrimaryKey(reqDto.getId());
            if(postSales.getIsSubmitOtherLogistics()){
                return ResultUtils.error("订单已填写物流信息");
            }
            if(!"1".equals(postSales.getStatus())){
                return ResultUtils.error("非售后中订单不支持填写");
            }
            LogisticsDto logisticsDto = new LogisticsDto();
            logisticsDto.setOrderId(postSales.getJdOrderId());
            logisticsDto.setThirdApplyId(postSales.getThirdApplyId());
            List<WaybillInfo> waybillInfoList = new ArrayList<>();
            WaybillInfo waybillInfo = new WaybillInfo();
            waybillInfo.setWareId(postSales.getSkuId());
            waybillInfo.setWareNum(postSales.getNum());
            waybillInfo.setWareType(10);
            waybillInfo.setExpressCompany(reqDto.getExpressCompany());
            waybillInfo.setExpressCode(reqDto.getExpressCode());
            waybillInfo.setDeliverDate(reqDto.getDeliverDate());
            waybillInfo.setFreightMoney(reqDto.getFreightMoney());
            waybillInfoList.add(waybillInfo);
            logisticsDto.setWaybillInfoList(waybillInfoList);
            String respStr = JDUtils.afterSaleNewUpdateSendInfo(logisticsDto);
            log.info("售后填写第三方订单信息结果，" + respStr);
            JSONObject respJson = JSONObject.parseObject(respStr);
            if ("true".equals(respJson.getString("success")) && "0000".equals(respJson.getString("resultCode"))) {
                PostSales updateBean = new PostSales();
                updateBean.setId(postSales.getId());
                updateBean.setIsSubmitOtherLogistics(true);
                postSalesMapper.updateByPrimaryKeySelective(updateBean);
                return ResultUtils.success("操作成功");
            }
        } catch (Exception e) {
            log.error("售后填写第三方订单信息，出错", e);
        }
        return ResultUtils.error("操作失败");
    }

    @PostMapping("checkOk")
    @ApiOperation(value = "确认售后")
    @ApiImplicitParams({@ApiImplicitParam(name = "jdOrderId", value = "京东订单id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thirdApplyId", value = "申请售后号", required = true, dataType = "String")})
    public ResultVO<JSONArray> checkOk(String jdOrderId, String thirdApplyId) {
        try {
            String respStr = JDUtils.afterSaleNewConfirmAfsOrder(jdOrderId, Arrays.asList(thirdApplyId));
            log.info("确认售后结果，" + respStr);
            JSONObject respJson = JSONObject.parseObject(respStr);
            if ("true".equals(respJson.getString("success")) && "0000".equals(respJson.getString("resultCode"))) {
                updateStatus(jdOrderId,thirdApplyId,"2");
                return ResultUtils.success("操作成功");
            }
        } catch (Exception e) {
            log.error("确认售后，出错", e);
        }
        return ResultUtils.error("操作失败");
    }

    @PostMapping("checkCancle")
    @ApiOperation(value = "取消售后")
    @ApiImplicitParams({@ApiImplicitParam(name = "jdOrderId", value = "京东订单id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "thirdApplyId", value = "申请售后号", required = true, dataType = "String")})
    public ResultVO<JSONArray> checkCancle(String jdOrderId, String thirdApplyId) {
        try {
            String respStr = JDUtils.afterSaleNewCancelAfsApply(jdOrderId, thirdApplyId);
            log.info("取消售后结果，" + respStr);
            JSONObject respJson = JSONObject.parseObject(respStr);
            if ("true".equals(respJson.getString("success")) && "0000".equals(respJson.getString("resultCode"))) {
                updateStatus(jdOrderId,thirdApplyId,"3");
                return ResultUtils.success("操作成功");
            }
        } catch (Exception e) {
            log.error("取消售后，出错", e);
        }
        return ResultUtils.error("操作失败");
    }

    private void updateStatus(String jdOrderId, String thirdApplyId,String status){
        PostSalesExample example = new PostSalesExample();
        example.createCriteria().andJdOrderIdEqualTo(jdOrderId).andThirdApplyIdEqualTo(thirdApplyId);
        PostSales updateBean = new PostSales();
        updateBean.setStatus(status);
        postSalesMapper.updateByExampleSelective(updateBean,example);
    }
}
